package com.ffyc.cemp.tools;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.Verification;

import java.util.Date;
import java.util.Map;

public class JwtUtils {

    private static JwtUtils instance = new JwtUtils();

    public static JwtUtils getInstance() {
        return instance;
    }

    /**
     * 创建token（令牌）
     *
     * @param data   数据
     * @param second 过期秒数
     * @param sign   数字签名
     * @return token字符
     */
    public String build(Map<String, Object> data, long second, String sign) {
        return JWT.create()
                .withClaim("data", data)
                .withExpiresAt(new Date(System.currentTimeMillis() + second * 1000))
                .sign(Algorithm.HMAC256(sign));
    }

    public Map<String,Object> verify(String sign, String token) {
        Verification require = JWT.require(Algorithm.HMAC256(sign));
        DecodedJWT verify = require.build().verify(token);
        Claim data = verify.getClaim("data");
        Map<String, Object> map = data.asMap();
        return map;
    }

}
